<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 
 *订单下载
 * @icon fa fa-circle-o
 */
class Orderdownload extends Backend
{

    /**
     * Orderdownload模型对象
     * @var \app\admin\model\Orderdownload
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orderdownload;
        $this->view->assign("isAgencyList", $this->model->getIsAgencyList());
        $this->view->assign("platformTypeList", $this->model->getPlatformTypeList());
        $this->view->assign("isCallbackList", $this->model->getIsCallbackList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("isRechargedList", $this->model->getIsRechargedList());
        $this->view->assign("baoxiaoStatusList", $this->model->getBaoxiaoStatusList());
        $this->view->assign("recoverStatusList", $this->model->getRecoverStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->whereNotNull('image')
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','is_agency','order_id','phone','image','call_image','audit_upload_time','platform_type']);
                
            }
            $download = $this->model->where($where)->where(['platform_type'=>1])->select();
            cache('download',$download);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function daochu(){
        $data = cache('download');
        $folderPath = 'orderImage/';
        // 创建文件夹
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0777, true);
        }
        foreach ($data as $k=>$v){
            if($v['image']){
                $imageUrl = $v['image'];
                $imageData = file_get_contents($imageUrl);
                if($imageData){
                    file_put_contents($folderPath . $v['order_id'].'.jpg', $imageData);
                }

            }
        }
// 创建压缩包
        $zip = new \ZipArchive();
        $end_dir = "orderDownload/" . date('YmdHis', time()) . '.zip';//定义打包后的包名
        if ($zip->open($end_dir, \ZipArchive::CREATE) === TRUE) {
            $this->addFileToZip($folderPath, $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法

            $zip->close(); //关闭处理的zip文件
            foreach ($data as $k=>$v){
                if($v['image']){
                    unlink($folderPath . $v['order_id'].'.jpg');
                }
            }
        }
        $file = $end_dir;
        $fileTmp = pathinfo($file);
        $fileExt = $fileTmp['extension'];
        $fp = fopen($file, "r");
        $saveFileName = $end_dir;
        $file_size = filesize($file);
        $url = 'https://'.$_SERVER['HTTP_HOST'];
        $this->success('ok','',['url'=>$url.'/'.trim($saveFileName,'.')]);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:" . $file_size);
        Header("Content-Disposition: attachment; filename=" . $saveFileName);
        $buffer = 1024;
        $file_count = 0;
        //向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
        exit;
    }

    private function addFileToZip($path, $zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。

        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..'，不要对他们进行操作
//                dump($path . "/" . $filename);
                $zip->addFile($path . "/" . $filename);
            }
        }
        @closedir($path);
    }

}
